var $productRoyList=$("#productRoyTable")
// 表格高度
var globalHeight;


$(function () {
    globalHeight = $(window).height() - $('#productRoyTable').offset().top - 30 - 25;
    productRoyTableFun()
    $('.datepicker').datepicker({
        language: "zh-CN",
        autoclose: true,
        clearBtn: true,
        todayHighlight: true,
        format: "yyyy-mm-dd"
    });
})

/**
 * 功能：缩放页面重绘table高度
 * */
$(window).resize(debounce(resizeTable, 500));
function resizeTable() {
    // 计算初始表格高度 = 浏览器高度 - 表格距浏览器顶部高度 - 主体底部padding+margin
    // 注：表格距浏览器顶部高度此处用最外层div获取，解决table垂直滚动时距离
    globalHeight = $(window).height() - $('.bootstrap-table').offset().top - 30 - 25;
    $('#productRoyTable').bootstrapTable('resetView', {height: globalHeight});
}


function indexFormat(value, row, index) {
    return index + 1;
}
function genderOptPro(value, row, index) {
    let html = '';
    html += '<button type="button" class="btn btn-default" style="width: 40px;visibility:hidden;"></button>';
    html += '<button type="button" class="btn btn-default" id="editProduct">修改</button>';

    return html
}

function genderOptinput(value, row, index) {
    let html = '';
    if(row.royaltyMoney==undefined){
        html += '<div style="width: 100px">-</div>';
    }else{
        html += '<div style="width: 100px">'+row.royaltyMoney+'</div>';
    }




    return html
}

function royaltyStatusHtml(value, row, index) {
    if(row.royaltyStatus==0){
        return '未发放'
    }else if(row.royaltyStatus==1){
        return '已发放'
    }else{
        return '-'
    }
}



var editInfoPro={
    //修改
    'click #editProduct': function(e, value, row, index) {
        $("#finishOrderProductId").val(row.finishOrderProductId)
        $("#MoneyModels").modal('show')
        $("#royaltyMoney").val(row.royaltyMoney)
        $("#preservationProduct").show()

        if($(".Money-company").data('bootstrapValidator')!=undefined){
            $(".Money-company").data('bootstrapValidator').destroy();
            $('.Money-company').data('bootstrapValidator', null);
        }
        // if(row.royaltyMoney==undefined || row.royaltyMoney==null){
        //     $(e.target).parent().prev().html('<input type="text" value="" placeholder="请输入" class="form-control" >')
        // }else{
        //     $(e.target).parent().prev().html('<input type="text" value="'+row.royaltyMoney+'" placeholder="请输入" class="form-control" >')
        // }
        // //\''+e+'\',
        // $(e.target).parent().html('<input  type="button" class="btn btn-default" id="preservationId" value="保存"/><input type="button" class="btn btn-default" id="cancelId" onclick="delMoney(\'' + row.royaltyMoney + '\')" value="取消"/>')
    },


}
function delMoney(royaltyMoney) {

    // $(this).parent().html('<button type="button" class="btn btn-default" id="editProduct">修改</button>')
    // $productRoyList.bootstrapTable('refresh');
}

/**
 * 订单列表 --分页列表页
 */
function toOrderInfo(value, row, index) {
    if(value == null) {
        return '<span href="JavaScript:void(0);">-</span>';
    }else {
        //onclick=\'OrderDetail(\"'+row.orderNumber+'")\'
        return '<a href="JavaScript:void(0);" onclick=\'OrderDetail(\"'+row.productOrderNum+'")\'>'+value+'</a>';
    }
}
function OrderDetail(orderNumber) {
    parent.$(parent.document).data('multitabs').create({
        iframe: true,
        title: '订单详情',
        url: "/front/finance/orderInfoByNumber?productOrderNumber="+orderNumber
    },true);
}

function productRoyTableFun() {
    $productRoyList.bootstrapTable('destroy');
    $productRoyList.bootstrapTable({
        //table table-bordered table-hover table-striped
        classes: 'table table-hover table-bordered table-striped',
        url: '/finishOrderProduct/selectFinishOrderProductList',//请求地址
        method: 'post',//请求方式
        contentType: "application/x-www-form-urlencoded",//请求内容类型
        dataType: "json",//数据类型
        striped: false,//是否显示行间隔色
        sortable: false,//是否启用排序
        sortOrder: "desc",//排序方式
        sortName: 'createTm',//排序字段
        cache: false,//是否使用缓存
        showColumns: false,//显示隐藏列
        showRefresh: false,//显示刷新按钮
        showToggle: false,//切换显示样式
        showFooter: false,//显示Table脚部
        pagination: true,//是否显示分页
        showPaginationSwitch: false,//是否显示分页按钮
        clickToSelect: false,//是否启用点击选中行
        singleSelect: false,
        minimumCountColumns: 2,//最少要显示的列数
        undefinedText: '-',//cell没有值时显示
        sidePagination: "server",//分页方式：client客户端分页，server服务端分页
        uniqueId: 'logId',
        idField: 'logId',
        pageSize: 10,//每页的记录行数
        pageNumber: 1,//初始化加载第1页，默认第1页
        pageList: "[10]",//可供选择的每页的行数

        fixedColumns: true,     // 冻结列
        fixedNumber: 2,         // 左侧固定列
        fixedRightNumber: 2,    // 右侧固定列
        height: globalHeight,
        queryParams: function (params) {
            params.pageSize = params.limit;
            params.pageIndex = (params.offset / params.limit) + 1;

            params.dateType = $('#dateType').val();//dateType(all:全部; thisWeek:本周; thisMonth:本月; thisYear:本年)
            //数据类型 提成发放的val = 1
            // params.dateStatusType = $("#dateStatusType").val();
            // //普通搜索条件
            // params.userName = $.trim($('#userNamep').val());//订单编号
            // //开始时间
            params.arriveTimeStart = $('#startTm').val();
            // //结束时间
            params.arriveTimeEnd = $('#endTm').val();

            // params.bs=0;
            return params;
        },//查询参数
        columns: [
            {title: '主键', field: 'logId', visible: false},
            {title: '序号', field: 'index', align: 'center', valign: 'left', width: '60', formatter: indexFormat},
            {title: '订单编号', field: 'productOrderNum', align: 'left', valign: 'middle', formatter: toOrderInfo},
            {title: '产品号', field: 'finishOrderProductNum', align: 'left', valign: 'middle'},
            {title: '产品名称', field: 'productName', align: 'left', valign: 'middle'},
            {title: '业绩金额', field: 'productFinalPrice', align: 'left', valign: 'middle'},
            {title: '换算比', field: 'ratio', align: 'left', valign: 'middle'},

            {title: '所有人', field: 'userName', align: 'left', valign: 'middle'},
            {title: '所属分公司', field: 'companyName', align: 'left', valign: 'middle'},
            {title: '完成时间', field: 'orderCompleteTm', align: 'left', valign: 'middle'},
            {title: '提成发布状态', field: 'royaltyStatus', align: 'left', valign: 'middle',formatter:royaltyStatusHtml},
            {title: '录入人', field: 'royaltyUerName', align: 'left', valign: 'middle'},
            {title: '最新录入时间', field: 'royaltyRecordTime', align: 'left', valign: 'middle'},
            {title: '提成金额', field: 'royaltyMoney', align: 'left', valign: 'middle', formatter:genderOptinput},


            {title: '操作', field: 'operate', align: 'right',width:'200',events: editInfoPro, formatter:genderOptPro}
        ],
        responseHandler: function (result) {
            if (result.code == "000000") {
                var obj = {
                    "rows": result.data,
                    "total": result.totalRecords//总条数
                };
            } else {
                var obj = {
                    "total": 0,
                    "rows": [],
                }
            }
            return obj;
        },
        onLoadSuccess: function () {

        },
        onLoadError: function (status) {
            if (status == 403) {
                alert("权限不足！禁止访问！");
            } else {
                //加载失败时执行
                alert("加载失败！");
            }
        },
        formatLoadingMessage: function () {
            return "请稍等，加载中...";
        },
        formatNoMatches: function () {
            return '无符合条件的记录';
        },
    });
}

function editMoneyCompany() {
    $('.Money-company').bootstrapValidator({
        excluded: [":disabled"],
        fields: {
            royaltyMoney: {
                validators: {
                    notEmpty: {
                        message: '提成金额不能为空'
                    }
                }
            },

        }
    })

    var bootstrapValidator = $(".Money-company").data('bootstrapValidator');
    bootstrapValidator.validate();
    if (!bootstrapValidator.isValid()) {
        return;
    }
    let jsonData={
        finishOrderProductId:$("#finishOrderProductId").val(),
        royaltyMoney:$("#royaltyMoney").val(),
    }
    $.ajax({
        type:"post",
        url:"/finishOrderProduct/updateFinishOrderProduct",
        contentType: "application/json;charset=utf-8",
        data: JSON.stringify(jsonData),
        dataType: 'json',
        async:false,
        success:function (data,status) {
            if(data.code=='000000'){
                $.alert(data.message);
                $("#MoneyModels").modal('hide')
                $productRoyList.bootstrapTable('refresh')
            }else{
                $.alert(data.message);
            }
        },
        error: (function (res) {
            $.alert("保存失败");
        })
    })
}

function exportProductFun() {
    var url = "/finishOrderProduct/exportFinishOrderProduct?dateType="+$('#dateType').val()+"&arriveTimeStart="+$('#startTm').val()+"&arriveTimeEnd="+$('#endTm').val()
    window.location.href=encodeURI(encodeURI(url));
}

function importProductFun() {

    $('#importFollowModal').modal('show');
}


/**
 * 导入
 */
function importFollow() {
    if(!document.getElementById('importFollowFile').files[0]){
        $.alert({
            title: '温馨提示',
            content: '请选择文件！',
        });
        return;
    }
    $(".btn-detail").attr("disabled",true)
    var fileName = document.getElementById('importFollowFile').files[0].name;
    var fileType = fileName.substring(fileName.lastIndexOf("."), fileName.length);
    var formData = new FormData();
    //接口接收参数 键值形式 添加到formData中
    formData.append("file",$("#importFollowFile")[0].files[0]);
    if(fileName!="" && (fileType.toLocaleUpperCase()==".XLSX"||fileType.toLocaleUpperCase()==".XLS")){
        $.ajax({
            url: '/finishOrderProduct/importOrderProductRoyalty',
            type: 'POST',
            dataType:"json",
            contentType:false,
            data: formData,
            processData: false,
            // uploadProgress: (function (event, position, total, percentComplete) {
            //     console.log(percentComplete,'percentComplete')
            //
            // }),
            success:(function(data) {
                if(data.code == "000000"){
                    $(".btn-detail").attr("disabled",false)
                    var importCallNum=data.data.importCallNum
                    var importFailIdStr=data.data.importFailIdStr
                    var content=''

                    //导入数量大于0
                    if(importCallNum>0){
                        content = "成功导入"+importCallNum+"条数据";
                    }
                    //失败id不为空
                    if(importFailIdStr!=""){
                        content = content + "<br>excel表格第：" + importFailIdStr + "行信息导入失败";
                    }
                    $.alert({
                        title: '提示',
                        content: content,
                        buttons: {
                            confirm: {
                                text: '确认',
                                btnClass: 'btn-primary',
                                action: function () {
                                    $("#importFollowFile").val("");
                                    $productRoyList.bootstrapTable('refresh');
                                }
                            }
                        }
                    });
                    $('#importFollowModal').modal('hide');
                    $("#importFollowModal").val("");
                }else if(data.code == "CI0001"){
                    $.alert({
                        title: '提示',
                        content: data.message,
                        buttons: {
                            confirm: {
                                text: '确认',
                                btnClass: 'btn-primary',
                                action: function () {
                                    $("#importFollowFile").val("");
                                }
                            }
                        }
                    });
                }else{
                    $.alert("导入失败");
                    $("#importFollowFile").val("");
                }
            }),
            error:(function() {
                $.alert("导入出错！");
                $("#importContractFile").val("");
            })
        });




    } else {
        $.alert({
            title: '温馨提示',
            content: '请上传.xlsx或.xls文件！',
        });
    }
}

/**
 * 取消导入
 */
function cancelImportFollow() {
    $("#importFollowFile").val("");
}


function selectTime(time) {
    if (time == 'all') {//全部
        $('.all').addClass('active-second');
        $('.year').removeClass('active-second');
        $('.week').removeClass('active-second');
        $('.month').removeClass('active-second');
        $('.topDay').removeClass('active-second');
        $('.day').removeClass('active-second');
        $('.customize').removeClass('active-second');
        $("#dateType").val("all");
        $('#customInput').css('display','none');
        $('#startTm').val('');
        $('#endTm').val('');
    }
    if (time == 'year') {//本年
        $('.year').addClass('active-second');
        $('.all').removeClass('active-second');
        $('.week').removeClass('active-second');
        $('.month').removeClass('active-second');
        $('.topDay').removeClass('active-second');
        $('.day').removeClass('active-second');
        $('.customize').removeClass('active-second');
        $("#dateType").val("thisYear");
        $('#customInput').css('display','none');
        $('#startTm').val('');
        $('#endTm').val('');
    }
    if (time == 'month') {//本月
        $('.month').addClass('active-second');
        $('.all').removeClass('active-second');
        $('.year').removeClass('active-second');
        $('.week').removeClass('active-second');
        $('.topDay').removeClass('active-second');
        $('.day').removeClass('active-second');
        $('.customize').removeClass('active-second');
        $("#dateType").val("thisMonth");
        $('#customInput').css('display','none');
        $('#startTm').val('');
        $('#endTm').val('');
    }
    if (time == 'week') {//本周
        $('.week').addClass('active-second');
        $('.all').removeClass('active-second');
        $('.year').removeClass('active-second');
        $('.month').removeClass('active-second');
        $('.topDay').removeClass('active-second');
        $('.day').removeClass('active-second');
        $('.customize').removeClass('active-second');
        $("#dateType").val("thisWeek");
        $('#customInput').css('display','none');
        $('#startTm').val('');
        $('#endTm').val('');
    }

    if (time == 'topDay') {//昨天
        $('.topDay').addClass('active-second');
        $('.week').removeClass('active-second');
        $('.all').removeClass('active-second');
        $('.year').removeClass('active-second');
        $('.month').removeClass('active-second');
        $('.day').removeClass('active-second');
        $('.customize').removeClass('active-second');
        $("#dateType").val("topDay");
        $('#customInput').css('display','none');
        $('#startTm').val('');
        $('#endTm').val('');
    }
    if (time == 'day') {//今天
        $('.day').addClass('active-second');
        $('.week').removeClass('active-second');
        $('.all').removeClass('active-second');
        $('.year').removeClass('active-second');
        $('.month').removeClass('active-second');
        $('.topDay').removeClass('active-second');
        $('.customize').removeClass('active-second');
        $("#dateType").val("day");
        $('#customInput').css('display','none');
        $('#startTm').val('');
        $('#endTm').val('');
    }
    if (time == 'customize') {//自定义
        $('.customize').addClass('active-second');
        $('.week').removeClass('active-second');
        $('.all').removeClass('active-second');
        $('.year').removeClass('active-second');
        $('.month').removeClass('active-second');
        $('.topDay').removeClass('active-second');
        $('.day').removeClass('active-second');
        $("#dateType").val("");
        // $('#customInput').show();

        if($("#customInput").is(":hidden")){
            $('#customInput').show();
        }else{
            $('#customInput').hide();
        }
        return;
    }
    $productRoyList.bootstrapTable('refreshOptions', {pageNumber: 1});
}

$("#customDateBtn").on('click',function () {
    $productRoyList.bootstrapTable('refreshOptions', {pageNumber: 1});
})

